require('../jquery.cookie.js');
let template = require('../plugins/art-template.js');
// 获取登录的id，判断有无权限
var id, token;
(function (){
	let userInfo = JSON.parse($.cookie('userdata'));
	id = userInfo.userdata.id;
	token = userInfo.userdata.token
})();

let actionUrl = {}
/*设置删除的url*/
function setDelUrl(url) {
	actionUrl.trDelUrl = url
}
function setEditorUrl(url) {
	actionUrl.trInfoUrl = url
}
function setEditorUpdateUrl(url) {
	actionUrl.editUpdateUrl = url
}


(function( $ ) {

	var EditableTable = {

		options: {
			table: '#demo-custom-toolbar',
			modal: '#editorModal',
			delbtn: '#demo-delete-row',
			dialog: {
				wrapper: '#dialog',
				cancelButton: '#dialogCancel',
				confirmButton: '#dialogConfirm',
			}
		},

		initialize: function(option) {
			this.options.table = option.table
			this.options.modal = option.modal
			this.options.option = option.option
			this
				.setVars()
				.build()
				.events();
		},

		setVars: function() {
			this.$id = parseInt(id)
			this.$modal = $( this.options.modal );
			this.$table				= $( this.options.table );
			this.$delbtn = $( this.options.delbtn );
			this.selectArray = [];
			// dialog
			this.dialog				= {};
			this.dialog.$wrapper	= $( this.options.dialog.wrapper );
			this.dialog.$cancel		= $( this.options.dialog.cancelButton );
			this.dialog.$confirm	= $( this.options.dialog.confirmButton );

			return this;
		},

		build: function() {
			this.datatable = this.$table

			window.dt = this.datatable;

			return this;
		},

		events: function() {
			var _self = this;
			this.$table
				.on('click', 'button.edit-row', function( e ) { //修改
					e.preventDefault();
					if(_self.$id === 1) {
						$(this).attr('data-target', _self.options.modal)
						var $row = $(this).closest( 'tr' );
						_self.$row = $row;
						let userid = $(this).attr('data-id');
						_self.$userid = userid;
						$.ajax({
							type: 'POST',
							url: actionUrl.trInfoUrl,
							data: {
								id: userid,
								token: token
							},
							dataType: "json",
							success: function(res) {
								console.log(res);
								if(res.status === 1) {
									if(res.msg === "获取成功") {
										if(/admin/g.test(actionUrl.trInfoUrl)) { //表示用户
											_self.$modal.find('input[name="name"]').val(res.data.username)
											_self.$modal.find('.select-group option[data-id='+res.data.groupid+']').attr('selected', true)
										}
										if(/rulegroup/g.test(actionUrl.trInfoUrl)) {
											_self.$modal.find('input[name="name"]').val(res.data.title)
											_self.$modal.find('textarea').val(res.data.content)
										}
									}
								}
								
							}
						})
					}else {
						layer.msg('您没有权限，请联系管理员', {time:500});
					}


				})
				.on( 'click', 'button.remove-row', function( e ) { //删除
					e.preventDefault();
					if(_self.$id === 1 ) {
						var $row = $(this).closest( 'tr' );
						var postdata = {};
						postdata.id = $(this).attr('data-id');
						postdata.token = token;
						$.magnificPopup.open({
							items: {
								src: _self.options.dialog.wrapper,
								type: 'inline'
							},
							preloader: false,
							modal: true,
							callbacks: {
								change: function() {
									_self.dialog.$confirm.on( 'click', function( e ) {
										e.preventDefault();

										_self.rowRemove( $row, postdata);
										$.magnificPopup.close();
									});
								},
								close: function() {
									_self.dialog.$confirm.off( 'click' );
								}
							}
						});
					}else {
						layer.msg('您没有权限，请联系管理员', {time:500});
					}
					
				});

			this.$table.on('click', 'input[name="btSelectAll"]', function() { //全选删除
				var trlength = _self.$table.find('tbody tr').length;
				_self.$trlength = trlength;
				if($(this).is(':checked')) {
					_self.selectArray = []
					$('input[name="btSelectItem"]').each(function(){                      
	                    $(this).prop("checked",true);
	                     _self.selectArray.push($(this).attr('data-id'));
	                });
					_self.$delbtn.prop('disabled', false)
				}else {
					_self.selectArray = []	
					$('input[name="btSelectItem"]').each(function(){  
	                    $(this).prop("checked",false); 
	                });
					_self.$delbtn.prop('disabled', true) 
				}
			})
			this.$table.on('click', 'input[name="btSelectItem"]', function(e) {
				var allSelectInput = _self.$table.find('input[name="btSelectAll"]')
				var trlength = _self.$table.find('tbody tr').length;
				_self.$trlength = trlength;
				if($(this).is(':checked') ) {
					let selectedId = $(this).attr('data-id');
					if(_self.selectArray.indexOf(selectedId) == -1) {
						_self.selectArray.push(selectedId)
					}	
				}else {
					allSelectInput.prop("checked",false)
					let selectedId = $(this).attr('data-id');
					let index = _self.selectArray.indexOf(selectedId);
					if(index > -1) {
						_self.selectArray.splice(index, 1)
					}
				}
				if(_self.selectArray.length === 0) {
					_self.$delbtn.prop('disabled', true)
				}else {
					if(_self.selectArray.length === _self.$trlength) {
						allSelectInput.prop("checked",true)
					}
					_self.$delbtn.prop('disabled', false)
				}
			})
			this.$delbtn.on('click', function(e) { //选中删除
				e.preventDefault();
				if(_self.$id === 1 ) {
					$.ajax({
						type: 'POST',
						url: actionUrl.trDelUrl,
						data: {
							id: _self.selectArray,
							token: token
						},
						dataType: "json",
						success: function(res) {
							if(res.status === 1) {
								if(res.msg === '删除成功') {
									_self.selectArray.forEach(v => {
										let $tr = _self.$table.find('input[data-id='+v+']').closest('tr')
										$tr.remove()
									})
									_self.selectArray = []
								}else {
									layer.msg('数据删除不成功，请稍后重试', {time:500});
								}
							}else {
								layer.msg('数据删除不成功，请稍后重试', {time:500});
							}
						}
					})
				}else {
					layer.msg('您没有权限，请联系管理员', {time:500});
					setTimeout(function(){
						_self.selectArray.forEach(v => {
							_self.$table.find('input[data-id='+v+']').prop('checked', false)
						})
						_self.$table.find('input[name="btSelectAll"]').prop('checked', false)
						_self.$delbtn.prop('disabled', true)
						_self.selectArray = []

					}, 800)
				}
			})
			this.dialog.$cancel.on( 'click', function( e ) {
				e.preventDefault();
				$.magnificPopup.close();
			});
			this.$modal.on('click', 'button.save-change', function(e) {
				e.preventDefault();
				if(/admin/g.test(actionUrl.trInfoUrl)) { //表示修改用户
					let post = {};
					post.token = token;
					post.id = _self.$userid;
					post.username = "" || _self.$modal.find('input[name="name"]').val();
					if(_self.$modal.find('input[name="password1"]').val().length == 0) {
						post.password = ""
					}else {
						post.password = _self.$modal.find('input[name="password1"]').val()
					}

					if(_self.$modal.find('input[name="password2"]').val().length == 0) {
						post.repassword = ""
					}else {
						post.repassword = _self.$modal.find('input[name="password2"]').val()
					}
					post.groupid = "" || _self.$modal.find('.select-group option:selected').attr('data-id');

					if(post.repassword === post.password) {
						_self.$modal.find('#title-error').addClass('hide')
						_self.submit(post, _self.$row)

					}else {
						_self.$modal.find('#title-error').removeClass('hide')
					}
					
					
				}
				if(/rulegroup/g.test(actionUrl.trInfoUrl)) {
					let post = {};
					post.token = token;
					post.id = _self.$userid;
					post.title = "" || _self.$modal.find('input[name="name"]').val();
					post.content = "" || _self.$modal.find('textarea').val();
					_self.submit(post, _self.$row)
				}
			})
			return this;
		},

		submit: function(post, $row) {
			var _self = this;
			$.ajax({
				type: 'POST',
				url: actionUrl.editUpdateUrl,
				data: post,
				dataType: "json",
				success: function(res) {
					if(res.status === 1) {
						_self.$modal.modal('hide')
						$.ajax({
							type: "POST",
							url: actionUrl.trInfoUrl,
							data: {
								id: _self.$userid,
								token: token
							},
							dataType: "json",
							success: function(res) {
								if(res.status === 1) {
									layer.msg('数据修改成功', {time:500});
									var $trhtml = template('update',res.data);
	                				$row.html($trhtml);

								}
							}
						})
					}else {
						_self.$modal.modal('show')
					}
				}
			})
		},

		rowRemove: function( $row, postdata) { //单个的删除
			var _self = this;
			if ( $row.hasClass('adding') ) {
				this.$addButton.removeAttr( 'disabled' );
			}
			
			/*发送删除的ajax请求*/
			$.ajax({
				type: 'POST',
				url:actionUrl.trDelUrl,
				data: postdata,
				dataType: "json",
				success: function(res) {
					if(res.status === 1) {
						_self.datatable.find($row).remove();
						layer.msg('删除成功', {time:500});
						
					}else {
						layer.msg('删除成功失败，稍后重试', {time:500});
						
					}
				}

			})	
		},
	};

	$(function() {
		EditableTable.initialize({
			table: '#demo-custom-toolbar', //表格的id
			modal: '#editorModal', //弹出修改的模态框
			delbtn: '#demo-delete-row'
		})
	});


}).apply( this, [$])



export {setDelUrl, setEditorUrl, setEditorUpdateUrl}